import { useState, useEffect } from 'react'
import Taro, { useShareAppMessage } from '@tarojs/taro'
import { View, Text, Image, ScrollView, Input } from '@tarojs/components'
import { Grid } from '@taroify/core'
import { FireOutlined, FilterOutlined, Exchange, VolumeOutlined } from '@taroify/icons'
import recipeService from '../utils/recipeService'
import './index.scss'

const Index = () => {
  const [recommendedRecipes, setRecommendedRecipes] = useState([])
  const [searchValue, setSearchValue] = useState('')
  const [hasLoadedData, setHasLoadedData] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState(null)

  useShareAppMessage(() => {
    return {
      title: '🍽️ 今天吃啥呢？',
      path: '/pages-recipe/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-cai-bg.jpg' // 替换为你的分享图片URL
    }
  })

  // 页面加载时从云端获取食谱数据
  useEffect(() => {
    const fetchData = async () => {
      if (!hasLoadedData) {
        try {
          setIsLoading(true)

          // 从云端获取食谱数据
          const recipeData = await recipeService.getRecipes()

          // 随机打乱菜谱数组并取前6个作为推荐
          const shuffled = [...recipeData].sort(() => 0.5 - Math.random())
          const selected = shuffled.slice(0, 6)
          setRecommendedRecipes(selected)
          setHasLoadedData(true)
        } catch (err) {
          console.error('获取食谱数据失败:', err)
          setError('获取食谱数据失败，请稍后再试')
          Taro.showToast({
            title: '加载失败，请重试',
            icon: 'none'
          })
        } finally {
          setIsLoading(false)
        }
      }
    }

    fetchData()
  }, [hasLoadedData])

  // 搜索处理
  const handleSearch = () => {
    if (searchValue && searchValue.trim()) {
      console.log('Searching for:', searchValue.trim())

      // 直接使用 navigateTo 而不是传递回调函数
      Taro.navigateTo({
        url: `/pages-recipe/search?keyword=${encodeURIComponent(searchValue.trim())}`
      }).catch((err) => {
        console.error('导航错误:', err)
      })
    } else {
      console.log('搜索值为空')
    }
  }

  // 搜索按钮点击处理
  const handleSearchButtonClick = () => {
    console.log('搜索按钮被点击')
    handleSearch()
  }

  // 当搜索框内容变化时
  const handleSearchChange = (e) => {
    console.log('搜索输入变化:', e.detail.value)
    setSearchValue(e.detail.value)
  }

  // 转到指定页面
  const navigateTo = (path, params = {}) => {
    const query = Object.keys(params)
      .map((key) => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')

    const url = query ? `${path}?${query}` : path
    Taro.navigateTo({ url })
  }

  // 查看菜谱详情
  const viewRecipeDetail = (id) => {
    navigateTo('/pages-recipe/detail', { id })
  }

  // 随机推荐一道菜
  const getRandomRecipe = () => {
    navigateTo('/pages-recipe/generate', { mode: 'random' })
  }

  // 按食材选菜
  const selectByIngredients = () => {
    navigateTo('/pages-recipe/ingredients')
  }

  return (
    <View className='recipe-home'>
      {/* 加载状态和错误提示 */}
      {isLoading && (
        <View className='loading-container'>
          <Text className='loading-text'>正在加载美食数据...</Text>
        </View>
      )}

      {error && (
        <View className='error-container'>
          <Text className='error-text'>{error}</Text>
          <View className='retry-button' onClick={() => setHasLoadedData(false)}>
            重试
          </View>
        </View>
      )}

      {!isLoading && !error && (
        <>
          {/* 顶部搜索区域 */}
          <View className='search-container'>
            <View className='search-input-box'>
              <Input
                value={searchValue}
                placeholder='搜索菜谱名称或食材'
                onInput={handleSearchChange}
                className='search-input'
                confirmType='search'
                onConfirm={handleSearch}
              />
            </View>
            <View className='custom-search-btn' onClick={handleSearchButtonClick}>
              搜索
            </View>
          </View>

          {/* 快捷功能区 */}
          <View className='feature-section'>
            <Grid columns={2} gutter={10} clickable>
              <Grid.Item icon={<Exchange />} text='随机一道菜' onClick={getRandomRecipe} />
              <Grid.Item icon={<FilterOutlined />} text='剩啥吃啥' onClick={selectByIngredients} />
            </Grid>
          </View>

          {/* 今日推荐 */}
          <View className='section-title'>
            <FireOutlined color='#ff6b6b' />
            <Text className='title-text'>今日推荐</Text>
          </View>

          <ScrollView className='recommended-recipes' scrollX>
            {recommendedRecipes.map((recipe) => (
              <View key={recipe.id} className='recipe-card' onClick={() => viewRecipeDetail(recipe.id)}>
                <Image className='recipe-image' src={recipe.image} mode='aspectFill' />
                <View className='recipe-info'>
                  <Text className='recipe-name'>{recipe.name}</Text>
                  <View className='recipe-tags'>
                    {recipe.tags.slice(0, 2).map((tag, index) => (
                      <Text key={index} className='tag'>
                        {tag}
                      </Text>
                    ))}
                  </View>
                </View>
              </View>
            ))}
          </ScrollView>

          {/* 每日提示 */}
          <View className='daily-tip'>
            <View className='tip-header'>
              <VolumeOutlined color='#4a90e2' />
              <Text className='tip-title'>烹饪小贴士</Text>
            </View>
            <Text className='tip-content'>
              炒青菜时加少许盐，能保持翠绿的色泽。家常菜煮汤时，放入几片姜片可减少油腻感。
            </Text>
          </View>

          {/* 热门分类 */}
          <View className='section-title'>
            <FireOutlined color='#ff6b6b' />
            <Text className='title-text'>热门分类</Text>
          </View>
          <View className='category-section'>
            <View className='category-item' onClick={() => navigateTo('/pages-recipe/search', { tag: '家常菜' })}>
              <Text className='category-name'>家常菜</Text>
            </View>
            <View className='category-item' onClick={() => navigateTo('/pages-recipe/search', { tag: '甜品' })}>
              <Text className='category-name'>甜品</Text>
            </View>
            <View className='category-item' onClick={() => navigateTo('/pages-recipe/search', { tag: '简单' })}>
              <Text className='category-name'>快手菜</Text>
            </View>
            <View className='category-item' onClick={() => navigateTo('/pages-recipe/search', { tag: '咸鲜' })}>
              <Text className='category-name'>下饭菜</Text>
            </View>
          </View>

          {/* 底部版权 */}
          <View className='footer'>
            <Text className='footer-text'>温馨提示：菜谱仅供参考，调整配料可获得更佳口感</Text>
          </View>
        </>
      )}
    </View>
  )
}

export default Index
